package com.wingbow.ticket;

import com.wingbow.ticket.message.Message;

import io.vertx.core.http.ServerWebSocket;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

@Data
@Slf4j
public class HostWebSocket {

    private ServerWebSocket serverWebSocket;
    private String roomId;

    public static void handle(ServerWebSocket serverWebSocket, String roomId) {
        if (!Client.hostMap.containsKey(roomId)) {
            Client.hostMap.put(roomId, new CustomServerWebSocket(serverWebSocket));
        } else {
            String newId = serverWebSocket.textHandlerID();
            String olId = Client.terminalMap.get(roomId).getServerWebSocket().textHandlerID();
            if (!newId.equals(olId)) {
                serverWebSocket.close();
                return;
            }
        }
        log.info("有新的连接加入，{}", serverWebSocket.textHandlerID());
        serverWebSocket.writeTextMessage("hello，this is server");

        serverWebSocket.textMessageHandler(message -> {
            log.info("server收到host消息,roomId:{},message:{}", roomId, message);
            // checkMessage(serverWebSocket, roomId, message);
            CustomServerWebSocket terminalWebSocket = Client.terminalMap.get(roomId);
            if (terminalWebSocket == null) {
                log.error("{}转发消息失败，对应的终端机还没起来", roomId);
                return;
            }
            terminalWebSocket.getServerWebSocket().writeTextMessage(message);
        });

        serverWebSocket.pongHandler(e -> {
            log.info("pong消息，{}", e);
        });

        serverWebSocket.closeHandler(c -> {
            log.info("socket 关闭了,roomId:{}", roomId);
            Client.hostMap.remove(roomId);
        });

        serverWebSocket.endHandler(end -> {
            log.info("end 操作");
        });

        serverWebSocket.exceptionHandler(ex -> {
            ex.printStackTrace();
        });
    }

    protected boolean checkMessage(ServerWebSocket serverWebSocket, String roomId, String message) {
        try {
            Message msg = JsonUtil.fromJSON(message, Message.class);
            if (!msg.getClientId().equals(roomId)) {
                serverWebSocket.writeTextMessage(JsonUtil.pojo2Json(Message.errMsg));
                return false;
            }

            if (msg.getType() != Message.reg) {
                CustomServerWebSocket customServerWebSocket = Client.hostMap.get(roomId);
                if (customServerWebSocket == null) {
                    serverWebSocket.writeTextMessage(JsonUtil.pojo2Json(Message.errMsg));
                    return false;
                }
            }
        } catch (Exception e) {
            serverWebSocket.writeTextMessage(JsonUtil.pojo2Json(Message.errMsg));
            return false;
        }

        return true;

    }
}
